#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time    : 2021/3/5 11:29
# @Author  : zhaohexin
# @Email   : 1483643520@xxx.com
# @File    : main.py
# @Software: PyCharm
# @FileDescription：通用接口校验

from datetime import timedelta

from fastapi import Depends, APIRouter, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from common.Depts import get_db
from core import settings
from apps.system.api import schemas
from apps.system.api import crud
from apps.system.users import crud as userCrue
from apps.system.roles import crud as roleCrud
from apps.system.jobs import crud as jobCrud
from apps.system.depts import crud as deptCrud
from apps.system.menus import crud as menuCrud
from apps.system.users import crud as userCrud
from common.ValidateCode import Captcha
from common.Redis import RedisCli

# from common.RedisCli import redis_client_user, redis_client_validate_code

router = APIRouter()


@router.get("/build")
async def build(db: Session = Depends(get_db), user_name: str = Depends(crud.check_token)):
    """
    登陆/刷新获取菜单层级目录
    :param db:
    :param user_name:
    :return:
    """
    user_id = userCrud.get_user_by_username(db, user_name).id
    role_id = [role.id for role in roleCrud.get_roles_by_user(db, user_id)]
    return menuCrud.get_build(db, role_id=role_id)


@router.post("/login_swagger", response_model=schemas.login, summary="登陆 - 配备接口校验 - 无验证码， 密码加密等")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    """
    获取token
    :param form_data:
    :param db:
    :return:
    """
    # 查询验证码是否正确
    user = crud.authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="未找到用户"
        )
    # 生成token
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = crud.create_access_token({"sub": user.username}, expires=access_token_expires)
    # 查询角色信息并进行赋值
    roles = roleCrud.get_roles_by_user(db, user_id=user.id)
    user_roles = [role.to_dict() for role in roles]
    roles_id = [role.id for role in roles]
    roles_permission = [role.data_scope for role in roles]
    # 查询岗位信息并进行赋值
    user_jobs = [job.to_dict() for job in jobCrud.get_jobs_by_user(db, user_id=user.id)]
    # 查询部门信息并进行赋值
    user_dept = deptCrud.get_dept(db, dept_id=user.dept_id).to_dict()
    # 获取部门权限列表
    if "全部" in roles_permission:
        dept_permission = []
    elif "本级" in roles_permission:
        dept_permission = [user.dept_id]
    else:
        dept_permission = [permission.dept_id for permission in deptCrud.get_dept_by_role(db, roles_id)]
    # 获取功能权限列表
    menu_permission = [menu.permission for menu in menuCrud.get_permission_by_role(db, roles_id) if menu.permission]
    user = user.to_dict()
    user["roles"] = user_roles
    user["jobs"] = user_jobs
    user["dept"] = user_dept
    data = {"token": access_token, "access_token": access_token,
            "user": {"dataScopes": dept_permission, "roles": menu_permission, "user": user}}
    return data


@router.post("/login", response_model=schemas.login, summary="登陆")
async def login_for_access_token(form_data: schemas.PostLogin, db: Session = Depends(get_db)):
    """
    获取token
    :param form_data:
    :param db:
    :return:
    """
    # 检验验证码
    crud.authenticate_img_code(form_data.uuid, form_data.code)
    # 校验用户名密码
    user = crud.authenticate_user(db, form_data.username, form_data.password)
    # 生成token
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = crud.create_access_token({"sub": user.username}, expires=access_token_expires)
    # 查询角色信息并进行赋值
    roles = roleCrud.get_roles_by_user(db, user_id=user.id)
    user_roles = [role.to_dict() for role in roles]
    roles_id = [role.id for role in roles]
    roles_permission = [role.data_scope for role in roles]
    # 查询岗位信息并进行赋值
    user_jobs = [job.to_dict() for job in jobCrud.get_jobs_by_user(db, user_id=user.id)]
    # 查询部门信息并进行赋值
    user_dept = deptCrud.get_dept(db, dept_id=user.dept_id).to_dict()
    # 获取部门权限列表
    if "全部" in roles_permission:
        dept_permission = []
    elif "本级" in roles_permission:
        dept_permission = [user.dept_id]
    else:
        dept_permission = [permission.dept_id for permission in deptCrud.get_dept_by_role(db, roles_id)]
    # 获取功能权限列表
    menu_permission = [menu.permission for menu in menuCrud.get_permission_by_role(db, roles_id) if menu.permission]
    user = user.to_dict()
    user["roles"] = user_roles
    user["jobs"] = user_jobs
    user["dept"] = user_dept
    data = {"token": f"{settings.TOKEN_HEAD} {access_token}", "access_token": access_token,
            "user": {"dataScopes": dept_permission, "roles": menu_permission, "user": user}}
    return data


@router.get("/code", summary="获取验证码")
def image_code():
    info = Captcha().create_image()
    # 连接redis
    redis = RedisCli("image_code")
    # 存储数据
    redis.__setitem__(info.get("uuid"), info.get("result"))
    return {
        "uuid": info.get("uuid"),
        "img": info.get("image")
    }


@router.get("/info", summary="获取用户信息")
async def user_info(db: Session = Depends(get_db), user_name: str = Depends(crud.check_token)):
    """
    获取用户信息
    :param db:
    :param user_name:
    :return:
    """
    user = userCrue.get_user_by_username(db, username=user_name)
    # 查询角色信息并进行赋值
    roles = roleCrud.get_roles_by_user(db, user_id=user.id)
    user_roles = [role.to_dict() for role in roles]
    roles_id = [role.id for role in roles]
    roles_permission = [role.data_scope for role in roles]
    # 查询岗位信息并进行赋值
    user_jobs = [job.to_dict() for job in jobCrud.get_jobs_by_user(db, user_id=user.id)]
    # 查询部门信息并进行赋值
    user_dept = deptCrud.get_dept(db, dept_id=user.dept_id).to_dict()
    # 获取部门权限列表
    if "全部" in roles_permission:
        dept_permission = []
    elif "本级" in roles_permission:
        dept_permission = [user.dept_id]
    else:
        dept_permission = [permission.dept_id for permission in deptCrud.get_dept_by_role(db, roles_id)]
    # 获取功能权限列表
    menu_permission = [menu.permission for menu in menuCrud.get_permission_by_role(db, roles_id) if menu.permission]
    user = user.to_dict()
    user["roles"] = user_roles
    user["jobs"] = user_jobs
    user["dept"] = user_dept
    data = {"dataScopes": dept_permission, "roles": menu_permission, "user": user}
    return data
